<?php
namespace Home\Controller;
use Think\Controller;
define("TOKEN", "add9f71512ba443b7405cf615d1cf5e0");
class IndexController extends Controller {
    public function index(){
       //$this->valid();//在微信平台上修改基本配置后提交时会用来验证，之后就不用了
    	$this->responseMsg();
    }
    public function valid(){
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }
    public function responseMsg(){
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $type = $postObj->MsgType;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>"; 
                if($type == 'event' && $postObj->Event == "subscribe" ){
                    $msgType = "text";
                    $contentStr = "欢迎关注!";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }            
				if($keyword == '哈哈' ){
              		$msgType = "text";
                	$contentStr = "小美女快来玩啊!";
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                }

                
                $articles = M('article')->where(array('keyword'=>$keyword))->select();
                if(!empty($articles)){
                    $textTpl = '<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>%s</ArticleCount>
                    <Articles>';
                    foreach ($articles as $a) {
                    $textTpl .= '<item>
                    <Title><![CDATA['.$a["title"].']]></Title> 
                    <Description><![CDATA['.$a["description"].']]></Description>
                    <PicUrl><![CDATA['.$a["picurl"].']]></PicUrl>
                    <Url><![CDATA['.$a["url"].']]></Url>
                    </item>';
                    }
                    $textTpl .= '</Articles>
                    </xml>';
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, count($articles));
                    echo $resultStr;
                }else{
                    $msgType = "text";
                    $contentStr =  http_get('http://www.xiaodoubi.com/simsimiapi.php?msg='.$keyword);
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }

        }else {
                echo "";
                exit;
        	
        }
    }
    
	public function createMenu(){
       $access_token = getAccessToken();
       $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$access_token;
        $data = array(
            'button'=>array(
                array(
                    'name'=>'发图',
                    'sub_button'=>array(
                        array(
                            'type'=>'pic_sysphoto',
                            'name'=>'系统拍照发图',
                            'key'=>'rselfmenu_1_0',
                            ),
                        array(
                            'type'=>'pic_photo_or_album',
                            'name'=>'拍照或者相册发图',
                            'key'=>'rselfmenu_1_1',
                            ),
                        array(
                            'type'=>'pic_weixin',
                            'name'=>'微信相册发图',
                            'key'=>'rselfmenu_1_2',
                            )
                        )
                    ),
                array(
                    'name'=>'扫码',
                    'sub_button'=>array(
                        array(
                            'type'=>'scancode_waitmsg',
                            'name'=>'扫码带提示',
                            'key'=>'rselfmenu_0_0',
                            ),
                        array(
                            'type'=>'scancode_push',
                            'name'=>'扫码推事件',
                            'key'=>'rselfmenu_1_1',
                            )
                        )
                    ),
                array(
                    "name"=>"发送位置", 
                    "type"=>"location_select", 
                    "key"=>"rselfmenu_2_0"    
                    )
                )
            );

        // $url = 'https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$access_token;
        $data = json_encode($data,JSON_UNESCAPED_UNICODE);
        $a = http_post($url,$data);
        var_dump($a);

    }
    public function text(){
        $keyword="小黄";
        $url = 'http://www.xiaodoubi.com/simsimiapi.php?msg='.$keyword;
        $s = file_get_contents($url);
        var_dump($s);
    }
	private function checkSignature()
	{
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        		
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );
		
		if( $tmpStr == $signature ){
			return true;
		}else{
			return false;
		}
	}
}